package com.ilovepostcard.view;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.ilovepostcard.Actions;
import com.ilovepostcard.HomeActivity;
import com.ilovepostcard.MainActivity;
import com.ilovepostcard.R;
import com.ilovepostcard.controller.ServerAsyncTask;
import com.ilovepostcard.controller.UserController;
import com.ilovepostcard.controller.server.IServer;
import com.ilovepostcard.controller.server.PostcardResult;
import com.ilovepostcard.controller.server.ServerFactory;
import com.ilovepostcard.model.User;
import com.ilovepostcard.utils.Constants;
import com.ilovepostcard.utils.ImageUtil;
import com.ilovepostcard.utils.StringUtils;
import com.ilovepostcard.utils.Utils;

public class PostcardRegisterView extends LinearLayout {
    
    private Bitmap mHeadBitmap;
    private ImageView headView;

    public PostcardRegisterView(Context context, AttributeSet attrs) {
        super(context, attrs);
        inflate();
    }

    public PostcardRegisterView(Context context) {
        super(context);
        inflate();
    }

    private static boolean isEmail(String str) {
        String strPattern = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"; 
        Pattern pattern = Pattern.compile(strPattern); 
        Matcher m = pattern.matcher(str); 
        return m.matches();
    }
    
    private void inflate() {
        View view = View.inflate(getContext(), R.layout.postcard_register, this);
        headView = (ImageView)view.findViewById(R.id.register_user_photo);
        headView.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                String[] arg0 = { getContext().getString(R.string.camera), getContext().getString(R.string.gallery) };
                Utils.showChooseDialog(getContext(), arg0, new Runnable[] {
                    new Runnable() {

                        @Override
                        public void run() {
                            ImageUtil.getImageFromCamera((Activity)getContext());
                        }
                        
                    },
                    new Runnable() {

                        @Override
                        public void run() {
                            ImageUtil.setImageFromGallery((Activity)getContext());
                        }
                        
                    }
                });
            }
        });
        
        final EditText emailView = (EditText)view.findViewById(R.id.register_email);
        final EditText nicknameView = (EditText)view.findViewById(R.id.register_nickname);
        final EditText pwdView = (EditText)view.findViewById(R.id.register_password);
        view.findViewById(R.id.register_button).setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                final String email = emailView.getText().toString().trim();
                final String nickname = nicknameView.getText().toString().trim();
                final String pwd = pwdView.getText().toString();
                if (StringUtils.isEmpty(email)) {
                    Toast.makeText(getContext(), R.string.notify_input_email, Toast.LENGTH_SHORT).show();
                    emailView.requestFocus();
                    return;
                }
                if (!isEmail(email)) {
                    Toast.makeText(getContext(), "请输入有效的邮箱", Toast.LENGTH_SHORT).show();
                    emailView.requestFocus();
                    return;
                }
                if (StringUtils.isEmpty(nickname)) {
                    Toast.makeText(getContext(), R.string.notify_input_nickname, Toast.LENGTH_SHORT).show();
                    nicknameView.requestFocus();
                    return;
                }
                /*用户不需要此限制
                 * if (nickname.length() < 6 || nickname.length() > 30) {
                    Toast.makeText(getContext(), "昵称必须介于6-30个字之间", Toast.LENGTH_SHORT).show();
                    nicknameView.requestFocus();
                    return;
                }*/
                if (StringUtils.isEmpty(pwd)) {
                    Toast.makeText(getContext(), R.string.notify_input_pwd, Toast.LENGTH_SHORT).show();
                    pwdView.requestFocus();
                    return;
                }
                if (pwd.length() < 6 || pwd.length() > 30) {
                    Toast.makeText(getContext(), "密码少于6位，请修改", Toast.LENGTH_SHORT).show();
                    pwdView.requestFocus();
                    return;
                }
                
                new ServerAsyncTask(getContext()) {
                    
                    @Override
                    protected void onSuccess(PostcardResult result) {
                        if (mHeadBitmap == null) {
                            Toast.makeText(context, R.string.register_success, Toast.LENGTH_LONG).show();
                            
                            new ServerAsyncTask(getContext()) {
                                
                                @Override
                                protected void onSuccess(PostcardResult result) {
                                    User user = new User();
                                    /* the result is uid */
                                    user.UserID = result.getResult();
                                    user.Username = email;
                                    UserController.saveLoginUser(context, user);
                                    /* now only used to notify the LoginActivity to finish itself. */
                                    context.sendBroadcast(new Intent(Actions.ACTION_LOGIN_SUCCESS));
                                    ((Activity)context).finish();
                                    Intent intent = new Intent(context, MainActivity.class);
                                    context.startActivity(intent);
                                }
                                
                                @Override
                                protected PostcardResult doRequest() {
                                    return ServerFactory.getServer().login(email, pwd);
                                }
                            }.execute();
                            
                            
//                            Activity activity = (Activity) context;
//                            Intent data = new Intent();
//                            data.putExtra("email", email);
//                            data.putExtra("pwd", pwd);
//                            activity.setResult(HomeActivity.RESULT_CODE_REGISTER_SUCCESS, data);
//                            activity.finish();
                        } else {
                            final long uid = result.getResult();
                            /* need upload head image first */
                            new ServerAsyncTask(getContext()) {
                                
                                @Override
                                protected void onSuccess(PostcardResult result) {
                                    final String skey = result.getUploadSKey();
                                    new ServerAsyncTask(getContext()) {
                                        
                                        @Override
                                        protected void onSuccess(PostcardResult result) {
                                            Toast.makeText(context, R.string.register_success, Toast.LENGTH_LONG).show();
//                                            Activity activity = (Activity) context;
//                                            Intent data = new Intent();
//                                            data.putExtra("email", email);
//                                            data.putExtra("pwd", pwd);
//                                            activity.setResult(HomeActivity.RESULT_CODE_REGISTER_SUCCESS, data);
//                                            activity.finish();
                                            
                                            new ServerAsyncTask(getContext()) {
                                                
                                                @Override
                                                protected void onSuccess(PostcardResult result) {
                                                    User user = new User();
                                                    /* the result is uid */
                                                    user.UserID = result.getResult();
                                                    user.Username = email;
                                                    UserController.saveLoginUser(context, user);
                                                    /* now only used to notify the LoginActivity to finish itself. */
                                                    context.sendBroadcast(new Intent(Actions.ACTION_LOGIN_SUCCESS));
                                                    ((Activity)context).finish();
                                                    Intent intent = new Intent(context, MainActivity.class);
                                                    context.startActivity(intent);
                                                }
                                                
                                                @Override
                                                protected PostcardResult doRequest() {
                                                    return ServerFactory.getServer().login(email, pwd);
                                                }
                                            }.execute();
                                        }
                                        
                                        @Override
                                        protected PostcardResult doRequest() {
                                            File file = new File(Constants.APP_DIR);
                                            if (!file.exists()) {
                                                file.mkdirs();
                                            }
                                            File headImageFile = new File(file, "head.jpg");
                                            FileOutputStream fos = null;
                                            try {
                                                fos = new FileOutputStream(headImageFile);
                                                mHeadBitmap.compress(CompressFormat.JPEG, 100, fos);
                                            } catch (IOException e) {
                                                
                                            } finally {
                                                if (fos != null)
                                                    try { fos.close(); } catch (Exception e2) { }
                                            }
                                            if (headImageFile.exists() && headImageFile.length() > 0)
                                                return ServerFactory.getServer().uploadFile(IServer.FILE_TYPE_HEAD_IMAGE, "head_"+nickname+".jpg", skey, uid, 0, 0, 100, 100, 0, headImageFile);
                                            return null;
                                        }
                                    }.execute();
                                }
                                
                                @Override
                                protected PostcardResult doRequest() {
                                    return ServerFactory.getServer().getUploadSKey();
                                }
                            }.execute();
                        }
                    }
                    
                    @Override
                    protected PostcardResult doRequest() {
                        return ServerFactory.getServer().register(email, pwd, nickname);
                    }
                }.execute();

            }
        });
    }
    
    public void setHeadImage(Bitmap bitmap) {
        mHeadBitmap = bitmap;
        headView.setImageBitmap(bitmap);
    }
}
